# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from openerp import SUPERUSER_ID

suit_dict = dict([(1, u'选项1'), (2, u'选项2'), (3, u'选项3'), (4, u'选项4'),(5, u'选项5'), (6, u'选项6'),
                                   (7, u'选项7'),(8, u'选项8'), (9, u'选项9'), (10, u'选项10')])
class reserved_product_to_card_order(osv.osv_memory):
    _name = 'reserved.product.to.card.order'

    def _get_product_order_suite(self, cr, uid, ids, context=None):
        so_product_obj = self.pool.get('sale.order.card.product')
        suite_list = []
        for suit in list(set([product.get('suite') for product in so_product_obj.search_read(cr, uid, [('order_id', '=', context.get('active_id'))],
                                                ['suite'], context=context)])):
            suite_list.append((suit, suit_dict.get(suit)))
        return suite_list

    def onchange_suite_qty(self, cr, uid, ids, suite, qty, so_id, context=None):
        so_product_obj = self.pool.get('sale.order.card.product')
        if not suite:
            return {}
        suite_product = "<table class='oe_list_content'><tr><td class='oe_list_field_cell oe_list_field_selection'>产品</td>" \
                        "<td class='oe_list_field_cell oe_list_field_selection'>锁定数量</td>" \
                        "<td class='oe_list_field_cell oe_list_field_selection'>库存</td></tr>"
        so_product_list_dict = so_product_obj.search_read(cr, uid, [('order_id', '=', so_id), ('suite', '=', suite)],
                                   ['product_id', 'product_qty', 'suite_name'])
        product_ids = [product.get('product_id', [False])[0] for product in so_product_list_dict]
        model_data_obj = self.pool.get('ir.model.data')
        location_id = model_data_obj.xmlid_to_res_id(
            cr, SUPERUSER_ID, 'dftg_ext.stock_location_card_exchange')
        cr.execute("""SELECT product_id AS product_id,
                                              sum(qty) as qty 
                                              from stock_quant where product_id in %s and reservation_id is NULL
                                              AND location_id = %s AND so_id IS NULL 
                                              group by product_id
                                              """ % (str(product_ids).replace('[', '(').replace(']', ')'), location_id))
        product_quant_list = cr.dictfetchall()
        product_quant_dict = {product_quant.get('product_id'): product_quant.get('qty') for product_quant in product_quant_list}
        if not suite:
            return {'warning': {'title': u'警告', 'message': u'请选择锁定的套装！'}, 'value': {'reserved_qty': '1'}}
        suite_name = ''
        for so_product in so_product_list_dict:
            if so_product.get('product_qty') * qty > product_quant_dict.get(so_product.get('product_id', [False])[0], 0):
                return {'value': {'reserved_qty':  0}, 'warning': {'title': u'警告', 'message': u'库存不足！'}}
            suite_product += "<tr><td class='oe_list_field_cell oe_list_field_selection'> %s </td>" \
                             "<td class='oe_list_field_cell oe_list_field_selection'> %s</td> " \
                             "<td class='oe_list_field_cell oe_list_field_selection'> %s</td></tr>\n" %\
                             (so_product.get('product_id', [False, False])[1],
                              so_product.get('product_qty') * qty,
                              product_quant_dict.get(so_product.get('product_id', [False])[0], 0))
            if not suite_name and so_product.get('suite_name', False):
                suite_name = so_product.get('suite_name')
        suite_product += "</table>"
        if suite_name:
            return_val = {'value': {'suite_product':  suite_product, 'suite_name': suite_name}}
        else:
            return_val = {'warning': {'title': u'警告！', 'message': u'请在卡券提货产品里输入套装名称!'},
                          'value': {'suite': 0, 'reserved_qty': 0}}
        return return_val
    _columns = {
        'message': fields.text(u'提示信息'),
        'suite': fields.selection('_get_product_order_suite', ype="selection",  string=u'套装'),
        'suite_product': fields.html(u'套装产品信息'),
        'reserved_qty': fields.float(u'保留份数'),
        'suite_name': fields.char(u'套装名称'),
        'so_id': fields.many2one('sale.order', u'销售订单'),
    }

    def lock_quant(self, cr, uid, product_id, qty, so_id,context=None):
        model_data_obj = self.pool.get('ir.model.data')
        location_id = model_data_obj.xmlid_to_res_id(
            cr, SUPERUSER_ID, 'dftg_ext.stock_location_card_exchange')
        quant_obj = self.pool.get('stock.quant')
        for quant_row in quant_obj.search_read(cr, uid, [('reservation_id', '=', False),
                                                         ('product_id', '=', product_id),
                                                         ('so_id', '=', False),
                                                         ('location_id', '=', location_id)], ['id', 'qty'], context=context):
            if quant_row.get('qty') > qty:
                quant = quant_obj.browse(cr, uid, quant_row.get('id'), context=context)
                quant_obj._quant_split(cr, uid, quant, qty, context=context)
            quant_obj.write(cr, uid, quant_row.get('id'), {'so_id': so_id, 'reservation_id': -1}, context=context)
            qty = qty - quant_row.get('qty')
            if qty <= 0:
                break
        if qty > 0:
            raise osv.except_osv(u'错误', u"库存不足!")
        return True

    def lock_quant_to_card_order(self, cr, uid, product_qty_dict, so_id, context=None):
        for product_id, product_qty in product_qty_dict.iteritems():
            self.lock_quant(cr, uid, product_id, product_qty, so_id, context=context)
        return True

    def reserved_product_to_card_order(self, cr, uid, ids, context=None):
        package_obj = self.pool.get('product.package')
        so_product_obj = self.pool.get('sale.order.card.product')
        package_id = False
        for wizard in self.browse(cr, uid, ids, context=context):
            if wizard.reserved_qty <= 0:
                raise osv.except_osv(u'错误', u"保留数量必须大于零!")
            so_product_list_dict = so_product_obj.search_read(cr, uid,
                                                              [('order_id', '=', wizard.so_id.id),
                                                               ('suite', '=', wizard.suite)],
                                                              ['product_id', 'product_qty'])
            product_qty_dict = {product.get('product_id', [False, False])[0]:
                                product.get('product_qty') * wizard.reserved_qty for product in so_product_list_dict}
            self.lock_quant_to_card_order(cr, uid, product_qty_dict, wizard.so_id.id, context=context)
            package_id = package_obj.create(cr, uid, {'package_qty': wizard.reserved_qty, 'so_id': wizard.so_id.id,
                                                      'name': self.pool.get('ir.sequence').get(cr, uid, 'product_package_order'),
                                                      'product_name': wizard.suite_name, 'product_package_line': [(0,
                                                       False, {'product_id': product.get('product_id', [False])[0],
                                                      'product_name': product.get('product_id', [False, False])[1],
                                                      'product_qty': product.get('product_qty') * wizard.reserved_qty
                                                       }) for product in so_product_list_dict],
                                              }, context=context)
        return self.pool.get('product.package').return_action(cr, uid, package_id, 'dftg_ext', 'dftg_product_package_action',
                                                              'dftg_product_package_form', return_type='form',  context=context)

    def set_default_message(self, cr, uid, context=None):
        order = self.pool.get('sale.order').search_read(cr, uid, [('id', '=', context.get('active_id'))],
                                                        ['name'], context=context)
        return '为卡券销售订单%s锁定库存！' % order[0].get('name')

    _defaults = {
        'reserved_qty': 1,
        'so_id': lambda self, cr, uid, context=None: context.get('active_id'),
        'message': set_default_message,
    }




